﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace CPPEI.Coolzon.UI.DataPartLib
{
    public partial class DataPartGrid
    {
        /// <summary>
        /// 返回所有的叶子节点列表，此列表的顺序和grid的列顺序一致，数量也一致，用此列表可以定位数据所在的列号
        /// </summary>
        /// <param name="grid"></param>
        /// <param name="columns"></param>
        /// <returns></returns>
        protected List<GridColumn> BuildHeader(Grid grid, List<GridColumn> columns)
        {
            List<GridColumn> leafColumns = new List<GridColumn>();

            int maxDepth = CalculateDepth(columns);
            int leafCount = CalculateLeafCount(columns, leafColumns);

            // add header row definition
            for (int index = 0; index < maxDepth + 1; index++)
            {
                RowDefinition rowDefinition = new RowDefinition();
                rowDefinition.Height = new GridLength(Math.Floor(maxDepth == 0 ? XHeaderHeight : XHeaderHeight / (maxDepth + 1)));
                grid.RowDefinitions.Add(rowDefinition);
            }

            //计算列宽
            List<double> autoWidths = CalculateColumnAutoWidth(columns);
            double autoWidth = 0f;
            if (autoWidths.Any())
            {
                if (autoWidths.Count < leafCount)
                {
                    autoWidth = (XWidth - autoWidths.Sum()) / (leafCount - autoWidths.Count);
                }
            }
            else
            {
                autoWidth = XWidth / leafCount;
            }
            autoWidth = Math.Floor(autoWidth);
            // add header column definition
            for (int index = 0; index < leafCount; index++)
            {
                // 设置列宽
                ColumnDefinition columnDefinition = new ColumnDefinition();
                if (leafColumns[index].Width != null)
                {
                    columnDefinition.Width = new GridLength(leafColumns[index].Width.Value, GridUnitType.Pixel);
                }
                else
                {
                    columnDefinition.Width = new GridLength(1, GridUnitType.Star);
                }

                grid.ColumnDefinitions.Add(columnDefinition);
            }


            //Debug.WriteLine("total r:" + maxDepth + " c:" + leafCount);

            int curDepth = 0;
            int curBreadth = 0;
            for (int index = 0; index < columns.Count; index++)
            {
                GridColumn column = columns[index];
                AddHeaderContent(grid, column, curDepth, ref curBreadth, maxDepth, autoWidth);
            }

            return leafColumns;
        }

        /// <summary>
        /// 将列信息添加到表头上
        /// </summary>
        /// <param name="grid"></param>
        /// <param name="column">列定义信息</param>
        /// <param name="curDepth">列所在的深度值</param>
        /// <param name="curBreadth">列所处的广度值</param>
        /// <param name="maxDepth">总深度</param>
        private void AddHeaderContent(Grid grid, GridColumn column, int curDepth, ref int curBreadth, int maxDepth, double autoWidth)
        {
            int curColumnBreadth = curBreadth;
            int curColumnDepth = curDepth;

            TextBlock textBlock = new TextBlock();
            if(column.Caption != null)
            {
                textBlock.Text = column.Caption.Replace("\\n", Environment.NewLine);
            }
            SetTextFormat(textBlock, -1, column);

            Border border = new Border();
            SetRowStyle(border, -1, -1);


            if (curDepth == 0 && curBreadth == 0)
            {
                border.BorderThickness = XHeaderBorderThickness;
            }
            else if (curDepth == 0)
            {
                border.BorderThickness = new System.Windows.Thickness(0, XHeaderBorderThickness.Top, XHeaderBorderThickness.Right, XHeaderBorderThickness.Bottom);
            }
            else if (curBreadth == 0)
            {
                border.BorderThickness = new System.Windows.Thickness(XHeaderBorderThickness.Left, 0, XHeaderBorderThickness.Right, XHeaderBorderThickness.Bottom);
            }
            else
            {
                border.BorderThickness = new System.Windows.Thickness(0, 0, XHeaderBorderThickness.Right, XHeaderBorderThickness.Bottom);
            }
            border.Child = textBlock;

            if (!XIsShowHeaderBorder)
            {
                border.BorderThickness = new Thickness(0, 0, 0, 0);
            }

            grid.Children.Add(border);

            //Debug.WriteLine("add header:" + column.Caption + " r:" + curColumnDepth + " c:" + curColumnBreadth);
            Grid.SetRow(border, curColumnDepth);
            Grid.SetColumn(border, curColumnBreadth);

            gd.ColumnDefinitions[curColumnBreadth].Width = new GridLength(column.Width.HasValue ? column.Width.Value : autoWidth);
            if (column.Columns == null || column.Columns.Count == 0)
            {
                Grid.SetRowSpan(border, maxDepth - curDepth + 1);
                border.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
                border.Height = gd.RowDefinitions[curColumnDepth].Height.Value * (maxDepth - curDepth + 1);
                //Debug.WriteLine("add header row span:" + (maxDepth - curDepth + 1));

                if (curColumnDepth == 0)
                {
                    // 当时根节点时，默认广度+1，代表有一个默认的子节点
                    curBreadth++;
                }
            }
            else
            {
                int leafCount = CalculateLeafCount(column, null);
                curBreadth += leafCount;
                Grid.SetColumnSpan(border, leafCount);
                border.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
                border.Height = gd.RowDefinitions[curColumnDepth].Height.Value;

                //Debug.WriteLine("add header column span:" + leafCount);
            }

            if (column.Columns != null && column.Columns.Count > 0)
            {
                for (int index = 0; index < column.Columns.Count; index++)
                {
                    GridColumn subColumn = column.Columns[index];
                    AddHeaderContent(grid, subColumn, curColumnDepth + 1, ref curColumnBreadth, maxDepth, autoWidth);
                    curColumnBreadth++;
                }
            }
        }


        #region 计算列结构树的总深度

        private int CalculateDepth(List<GridColumn> columns)
        {
            int depth = 0;
            int maxDepath = 0;
            for (int index = 0; index < columns.Count; index++)
            {
                int tempDepath = CalculateDepth(columns[index], depth);
                if (tempDepath > maxDepath)
                {
                    maxDepath = tempDepath;
                }
            }
            depth = maxDepath;
            return depth;
        }

        private int CalculateDepth(GridColumn column, int curDepath)
        {
            int depth = curDepath;
            if (column.Columns == null || column.Columns.Count == 0)
            {
                return depth;
            }

            int maxSubDepth = curDepath + 1;
            for (int index = 0; index < column.Columns.Count; index++)
            {
                int tempDepth = CalculateDepth(column.Columns[index], curDepath + 1);
                if (tempDepth > maxSubDepth)
                {
                    maxSubDepth = tempDepth;
                }
            }
            depth = maxSubDepth;
            return depth;
        }

        #endregion

        #region 计算列结构树的末级节点数

        /// <summary>
        /// 
        /// </summary>
        /// <param name="columns"></param>
        /// <param name="leafColumns">记录叶子节点的列表，如果为空则不记录</param>
        /// <returns></returns>
        private int CalculateLeafCount(List<GridColumn> columns, List<GridColumn> leafColumns)
        {
            int count = 0;
            for (int index = 0; index < columns.Count; index++)
            {
                count += CalculateLeafCount(columns[index], leafColumns);
            }
            return count;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="column"></param>
        /// <param name="leafColumns">记录叶子节点的列表，如果为空则不记录</param>
        /// <returns></returns>
        private int CalculateLeafCount(GridColumn column, List<GridColumn> leafColumns)
        {
            int count = 1;
            if (column.Columns == null || column.Columns.Count == 0)
            {
                if (leafColumns != null)
                {
                    leafColumns.Add(column);
                }
                return count;
            }

            count = 0;
            for (int index = 0; index < column.Columns.Count; index++)
            {
                count += CalculateLeafCount(column.Columns[index], leafColumns);
            }
            return count;
        }

        private List<double> CalculateColumnAutoWidth(List<GridColumn> columns)
        {
            List<double> widths = new List<double>();
            var vColumns = columns.Where(p => p.Width.HasValue);
            if (vColumns.Any())
            {
                widths = vColumns.Select(p => p.Width.Value).ToList();
            }
            vColumns = columns.Where(p => p.Columns != null && p.Columns.Any());
            if (vColumns.Any())
            {
                vColumns.ToList().ForEach((a) =>
                {
                    widths.AddRange(CalculateColumnAutoWidth(a.Columns));
                });
            }
            return widths;
        }
        #endregion
    }
}
